import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';

export class ClientFunFactController extends BaseController {
  // 获取冷知识
  async getFunFact(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      // 方案1：使用原生SQL实现真正的随机（MySQL兼容）
      const trivia = await prisma.$queryRaw`
        SELECT id, title, content
        FROM trivia 
        ORDER BY RAND() 
        LIMIT 5
      `;

      ResponseUtils.success(res, trivia, '获取冷知识成功');
    } catch (error) {
      // 如果原生SQL失败，回退到应用层随机
      try {
        const fallbackTrivia = await prisma.trivia.findMany({
          where: {
            isActive: true
          },
          take: 20, // 获取更多数据以提高随机性
          select: {
            id: true,
            title: true,
            content: true,
            createdAt: true
          }
        });

        // 随机打乱并取前5条
        const shuffled = fallbackTrivia
          .sort(() => Math.random() - 0.5)
          .slice(0, 5);

        ResponseUtils.success(res, shuffled, '获取冷知识成功');
      } catch (fallbackError) {
        next(fallbackError);
      }
    }
  }
}